package com.itbour.web.action.goods;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.itbour.com.page.Page;
import com.itbour.common.base.BaseAction;
import com.itbour.common.log.ErrorLogger;
import com.itbour.common.util.StringUtils;
import com.itbour.def.MessageCode;
import com.itbour.def.MessageCodeConstants;
import com.itbour.def.MessageType;
import com.itbour.def.SystemConf;
import com.itbour.dto.com.AreaInfoDto;
import com.itbour.dto.goods.AttractionsDto;
import com.itbour.dto.goods.ResortDto;
import com.itbour.dto.goods.ResortPicDto;
import com.itbour.service.goods.GoodsService;
import com.opensymphony.xwork2.ActionContext;

/**
 * copyright pirate alliance team 2014
 * 
 * @author songyong
 */

public class GetGoodsListWebAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private GoodsService goodsService;
	private List<ResortDto> goodsList;
	private ResortDto resortDto;
	private String id;
	/**
	 * 削除行index
	 */
	private Integer resPicDelIndex;
	/**
	 * 削除行index
	 */
	private Integer attPicDelIndex;

	private Map<String, String> areaMap = new HashMap<String, String>();
	private Map<String, String> areaMap2 = new HashMap<String, String>();

	private AreaInfoDto areaDto;

	private String classification;

	private String parentid;

	private String showPreviewFlg;

	private String showMapFlg;

	private List<Map<String, String>> typeList = null;

	private String verifyId;

	private String goodsClass;

	private String delIds;

	public String getVerifyId() {
		return verifyId;
	}

	public void setVerifyId(String verifyId) {
		this.verifyId = verifyId;
	}

	public void prepare() {
		typeList = new ArrayList<Map<String, String>>();
		Map<String, String> map = new HashMap<String, String>();
		map.put("key", "1");
		map.put("value", "景点");
		typeList.add(map);

		Map<String, String> map2 = new HashMap<String, String>();
		map2.put("key", "2");
		map2.put("value", "大门");
		typeList.add(map2);

		Map<String, String> map3 = new HashMap<String, String>();
		map3.put("key", "3");
		map3.put("value", "商店");
		typeList.add(map3);

		Map<String, String> map4 = new HashMap<String, String>();
		map4.put("key", "4");
		map4.put("value", "厕所");
		typeList.add(map4);

		Map<String, String> map5 = new HashMap<String, String>();
		map5.put("key", "5");
		map5.put("value", "售票处");
		typeList.add(map5);

		Map<String, String> map6 = new HashMap<String, String>();
		map6.put("key", "6");
		map6.put("value", "游客服务中心");
		typeList.add(map6);

		Map<String, String> map7 = new HashMap<String, String>();
		map7.put("key", "7");
		map7.put("value", "停车场");
		typeList.add(map7);
	}

	public String homePageGoodsList() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("oldURL") != null) {
			session.remove("oldURL");
		}
		this.goodsList = this.goodsService.selectHomePageGoods();
		return SUCCESS;
	}

	public String logOut() {
		ActionContext.getContext().getSession().remove("user");
		return homePageGoodsList();
	}

	public String searchGoodById() {
		int id = Integer.valueOf(ServletActionContext.getRequest()
				.getParameter("id"));
		this.resortDto = this.goodsService.getGoodsDetailById(id);
		return SUCCESS;
	}

	public String displayGoodsById() {
		String id = ServletActionContext.getRequest().getParameter("id");
		if (id != null && id != "") {
			this.id = id;
			this.resortDto = this.goodsService.getGoodsDetailById(Long
					.valueOf(id));
		}
		return SUCCESS;
	}

	public String saveGoodsEdit() {
		if (StringUtils.isEmpty(resortDto.getImageUrl())) {
			resortDto.setImageUrl(SystemConf.getImageServerUrl() + goodsClass
					+ "/" + saveImageTemp(resortDto.getImageFile(), ""));
		}

		if (resortDto.getAttractionsList() != null) {
			for (AttractionsDto att : resortDto.getAttractionsList()) {
				if (StringUtils.isEmpty(att.getImageUrl())) {
					att.setImageUrl(SystemConf.getImageServerUrl() + goodsClass
							+ "/" + saveImageTemp(att.getImageFile(), ""));
				}
			}
		}
		resortDto.setGoodsClass(goodsClass);
		goodsService.saveGoodsInfo(resortDto, id);
		return SUCCESS;
	}

	/**
	 * <pre>
	 * 追加ボタン押下
	 * </pre>
	 * 
	 * @return "success"
	 */
	public String doAdd() {
		if (resortDto.getAttractionsList() != null) {
			resortDto.getAttractionsList().add(new AttractionsDto());
		} else {
			resortDto.setAttractionsList(new ArrayList<AttractionsDto>());
			resortDto.getAttractionsList().add(new AttractionsDto());
		}
		return SUCCESS;
	}

	/**
	 * <pre>
	 * 削除ボタン押下
	 * </pre>
	 * 
	 * @return "success"
	 */
	public String doDel() {
		// if (resortDto.getAttractionsList() != null
		// && resortDto.getAttractionsList().size() > 0 && delIndex != null
		// && delIndex < resortDto.getAttractionsList().size()) {
		// resortDto.getAttractionsList().remove(resortDto.getAttractionsList().get(delIndex));
		// }
		return SUCCESS;
	}

	public void goodsList() throws Exception {
		showPreviewFlg = null;
		HttpServletRequest request = ServletActionContext.getRequest();
		String pageNumber = request.getParameter("page");
		String pageSize = request.getParameter("rows");
		Map<String, Object> param = new HashMap<String, Object>();
		String id = request.getParameter("id");
		if (StringUtils.isNotEmpty(id)) {
			param.put("id", id);
		}
		String name = request.getParameter("name");
		if (StringUtils.isNotEmpty(name)) {
			param.put("name", name);
		}
		String state = request.getParameter("state");
		if (StringUtils.isNotEmpty(state)) {
			param.put("state", state);
		}
		param.put("class", goodsClass);
		Page page = goodsService.pageQuery(param, Integer.parseInt(pageNumber),
				Integer.parseInt(pageSize));
		HashMap<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("total", page.getTotalCount());
		resMap.put("rows", page.getResult());
		writeJSON(resMap);
	}

	public String newGoodsInit() {
		this.resortDto = new ResortDto();
		List<ResortPicDto> resortPicList = new ArrayList<ResortPicDto>();
		ResortPicDto dto = new ResortPicDto();
		dto.setNewAddFlag("1");
		resortPicList.add(dto);
		this.resortDto.setResortPicList(resortPicList);

		List<AttractionsDto> attractionsList = new ArrayList<AttractionsDto>();
		AttractionsDto dto2 = new AttractionsDto();
		attractionsList.add(dto2);
		this.resortDto.setAttractionsList(attractionsList);

		this.resortDto.setGoodsClass(goodsClass);
		return SUCCESS;
	}

	/**
	 * <pre>
	 * 景区图片追加ボタン押下
	 * </pre>
	 * 
	 * @return "success"
	 */
	public String doResortPicAdd() {
		if (resortDto.getResortPicList() != null) {
			ResortPicDto dto = new ResortPicDto();
			dto.setNewAddFlag("1");
			resortDto.getResortPicList().add(dto);
		} else {
			resortDto.setResortPicList(new ArrayList<ResortPicDto>());
			ResortPicDto dto = new ResortPicDto();
			dto.setNewAddFlag("1");
			resortDto.getResortPicList().add(dto);
		}
		return SUCCESS;
	}

	/**
	 * <pre>
	 * 景区图片削除ボタン押下
	 * </pre>
	 * 
	 * @return "success"
	 */
	public String doResortPicDel() {
		if (resortDto.getResortPicList() != null
				&& resortDto.getResortPicList().size() > 0
				&& resPicDelIndex != null
				&& resPicDelIndex < resortDto.getResortPicList().size()) {
			resortDto.getResortPicList().remove(
					resortDto.getResortPicList().get(resPicDelIndex));
		}
		return SUCCESS;
	}

	/**
	 * <pre>
	 * 景点追加ボタン押下
	 * </pre>
	 * 
	 * @return "success"
	 */
	public String doAttAdd() {
		if (resortDto.getAttractionsList() != null) {
			resortDto.getAttractionsList().add(new AttractionsDto());
		} else {
			resortDto.setAttractionsList(new ArrayList<AttractionsDto>());
			resortDto.getAttractionsList().add(new AttractionsDto());
		}
		return SUCCESS;
	}

	/**
	 * <pre>
	 * 景点削除ボタン押下
	 * </pre>
	 * 
	 * @return "success"
	 */
	public String doAttDel() {
		if (resortDto.getAttractionsList() != null
				&& resortDto.getAttractionsList().size() > 0
				&& attPicDelIndex != null
				&& attPicDelIndex < resortDto.getAttractionsList().size()) {
			resortDto.getAttractionsList().remove(
					resortDto.getAttractionsList().get(attPicDelIndex));
		}
		return SUCCESS;
	}

	/**
	 * 確定ボタン押下
	 */
	public String doResNew() {
		if (StringUtils.isEmpty(resortDto.getImageUrl())
				&& resortDto.getImageFile() != null) {
			resortDto.setImageUrl(SystemConf.getImageServerUrl() + goodsClass
					+ "/" + saveImageTemp(resortDto.getImageFile(), ""));
		}
		if (resortDto.getResortPicList() != null) {
			for (ResortPicDto att : resortDto.getResortPicList()) {
				if (StringUtils.isEmpty(att.getImageUrl())) {
					att.setImageUrl(SystemConf.getImageServerUrl() + goodsClass
							+ "/" + saveImageTemp(att.getImageFile(), ""));
				}
			}
		}
		if (resortDto.getAttractionsList() != null) {
			for (AttractionsDto att : resortDto.getAttractionsList()) {
				if (StringUtils.isEmpty(att.getImageUrl())
						&& att.getImageFile() != null) {
					att.setImageUrl(SystemConf.getImageServerUrl() + goodsClass
							+ "/" + saveImageTemp(att.getImageFile(), ""));
				}
				att.setSoundurl(att.getSoundFileUrl());
				if (StringUtils.isEmpty(att.getSoundFileUrl())
						&& att.getImageFile() != null) {
					att.setSoundurl(SystemConf.getSoundServerUrl() + goodsClass
							+ "/" + saveImageTemp(att.getSoundFile(), "mp3"));
				}
			}
		}
		id = goodsService.saveGoodsInfo(resortDto, id);
		return SUCCESS;
	}

	/**
	 * 获取代码下拉框
	 * 
	 * @throws Exception
	 */
	public void getCodesForCombox() throws Exception {
		// 0 获取classification，无参数
		// 1 获取classification的下一级，参数为classification，如果是国内则返回省，如果是其他分类则返回第一级子对象
		// 2 获取classification的下两级，参数为parentid［第一级的id］
		int resultType = 0;
		if (StringUtils.isEmpty(classification)
				&& StringUtils.isEmpty(parentid)) {
			resultType = 0;
		} else if (StringUtils.isNotEmpty(classification)
				&& StringUtils.isEmpty(parentid)) {
			resultType = 1;
		} else {
			resultType = 2;
		}

		// 国内 港澳台 日韩 东南亚 欧洲 美洲 大洋洲 非洲
		List<String> lst = new ArrayList<String>();
		lst.add("国内");
		lst.add("港澳台");
		lst.add("日韩");
		lst.add("东南亚");
		lst.add("欧洲");
		lst.add("美洲");
		lst.add("大洋洲");
		lst.add("非洲");

		List<Object> res = new ArrayList<Object>();
		if (resultType == 0) {

			Map<String, Object> defaultValue = new HashMap<String, Object>();
			defaultValue.put("id", "");
			defaultValue.put("text", "请选择");
			defaultValue.put("selected", true);
			defaultValue.put("leaf", "0");
			res.add(defaultValue);

			for (int i = 0; i < lst.size(); i++) {
				String one = lst.get(i);
				Map<String, Object> item = new HashMap<String, Object>();
				item.put("id", i);
				item.put("text", one);
				item.put("leaf", "0");
				res.add(item);
			}

		} else if (resultType == 1) {

			Map<String, Object> defaultValue = new HashMap<String, Object>();
			defaultValue.put("id", "");
			defaultValue.put("text", "请选择");
			defaultValue.put("selected", true);
			defaultValue.put("leaf", "0");
			res.add(defaultValue);
			// String codeTypeId = request.getParameter("codeTypeId");
			// List<SysCode> codeList = BaseDataManage.getCodeInfo(codeTypeId);
			Map<String, Object> param = new HashMap<String, Object>();
			int nClass = Integer.valueOf(classification);
			param.put("classification", lst.get(nClass));

			List<Map<String, Object>> rst = goodsService
					.selectAreaOfClassificationChild(param);
			if (null != rst && !rst.isEmpty()) {
				for (Map<String, Object> t : rst) {
					Map<String, Object> typeMap = new HashMap<String, Object>();
					typeMap.put("id", t.get("id"));
					typeMap.put("text", t.get("name"));
					typeMap.put("leaf", t.get("leaf"));
					res.add(typeMap);
				}
			}

		} else {

			Map<String, Object> defaultValue = new HashMap<String, Object>();
			defaultValue.put("id", "");
			defaultValue.put("text", "请选择");
			defaultValue.put("selected", true);
			defaultValue.put("leaf", "0");
			res.add(defaultValue);
			// String codeTypeId = request.getParameter("codeTypeId");
			// List<SysCode> codeList = BaseDataManage.getCodeInfo(codeTypeId);
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("parentid", parentid);

			List<Map<String, Object>> rst = goodsService
					.selectAreaOfClassificationChild2(param);
			if (null != rst && !rst.isEmpty()) {
				for (Map<String, Object> t : rst) {
					Map<String, Object> typeMap = new HashMap<String, Object>();
					typeMap.put("id", t.get("id"));
					typeMap.put("text", t.get("name"));
					typeMap.put("leaf", t.get("leaf"));
					res.add(typeMap);
				}
			}

		}

		writeJSON(res);
	}

	/**
	 * 获取代码下拉框
	 * 
	 * @throws Exception
	 */
	public void getCodesForComboxLabels() throws Exception {
		List<Object> res = new ArrayList<Object>();
		// Map<String, Object> defaultValue = new HashMap<String, Object>();
		// defaultValue.put("id", "");
		// defaultValue.put("text", "请选择");
		// defaultValue.put("selected", true);
		// res.add(defaultValue);
		Map<String, Object> param = new HashMap<String, Object>();
		if (goodsClass != null && goodsClass != "") {
			param.put("class", goodsClass);
		}
		List<Map<String, Object>> rst = goodsService.selectLabels(param);
		if (null != rst && !rst.isEmpty()) {
			for (Map<String, Object> t : rst) {
				Map<String, Object> typeMap = new HashMap<String, Object>();
				typeMap.put("id", t.get("id"));
				typeMap.put("text", t.get("labelname"));

				res.add(typeMap);
			}
		}
		writeJSON(res);
	}

	public String areaSave() {
		this.goodsService.saveArea(areaDto);
		return SUCCESS;
	}

	public String editGoodsInit() {
		if (ServletActionContext.getRequest().getParameter("id") != null) {
			long id = Long.valueOf(ServletActionContext.getRequest()
					.getParameter("id"));
			this.resortDto = this.goodsService.getGoodsDetailById(id);
			this.resortDto.setGoodsClass(goodsClass);
		}
		return SUCCESS;
	}

	public String doPreview() {
		long id = Long.valueOf(ServletActionContext.getRequest().getParameter(
				"id"));
		this.resortDto = this.goodsService.getGoodsDetailById(id);
		return SUCCESS;
	}

	public String mapPreview() {
		long id = Long.valueOf(ServletActionContext.getRequest().getParameter(
				"id"));
		this.resortDto = this.goodsService.getGoodsDetailById(id);
		return SUCCESS;
	}

	public void goodsVerify() throws Exception {
		if (StringUtils.isNotEmpty(verifyId)) {
			this.goodsService.goodsVerify(verifyId, 1);
			this.writeJSON("ok");
		}
	}

	public void cancelVerify() throws Exception {
		if (StringUtils.isNotEmpty(verifyId)) {
			this.goodsService.goodsVerify(verifyId, 0);
			this.writeJSON("ok");
		}
	}

	public void deleteGoods() throws Exception {
		goodsService.deleteGoodsInfo(resortDto, id, delIds);
		this.writeJSON("ok");
	}

	public String goodsInit() {
		return SUCCESS;
	}

	public List<ResortDto> getGoodsList() {
		return goodsList;
	}

	public void setGoodsList(List<ResortDto> goodsList) {
		this.goodsList = goodsList;
	}

	public ResortDto getResortDto() {
		return resortDto;
	}

	public void setResortDto(ResortDto resortDto) {
		this.resortDto = resortDto;
	}

	public GoodsService getGoodsService() {
		return goodsService;
	}

	public void setGoodsService(GoodsService goodsService) {
		this.goodsService = goodsService;
	}

	public Map<String, String> getAreaMap() {
		return areaMap;
	}

	public void setAreaMap(Map<String, String> areaMap) {
		this.areaMap = areaMap;
	}

	public Map<String, String> getAreaMap2() {
		return areaMap2;
	}

	public void setAreaMap2(Map<String, String> areaMap2) {
		this.areaMap2 = areaMap2;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	/**
	 * 图像保存
	 * 
	 * @return
	 */
	private String saveImageTemp(File image, String fielType) {
		String suf = ".jpg";
		String path = SystemConf.getImageRootDir();
		if ("mp3".equals(fielType)) {
			suf = ".mp3";
			path = SystemConf.getSoundRootDir();

		}

		Date date = new Date();
		// DateFormat df1 = new SimpleDateFormat("yyyyMMdd");
		DateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String tmpImagePath = df2.format(date)
				+ StringUtils.getFixLenthString(4) + suf;

		String fileUrl = StringUtils.linkFilePath(path, tmpImagePath);
		File saveFile = new File(fileUrl);

		if (image == null) {
			return "";
		}
		try {
			FileUtils.copyFile(image, saveFile);
		} catch (IOException e) {
			ErrorLogger.log(e, new MessageCode(MessageCodeConstants.E_00000001,
					MessageType.ERROR), "RegisterAction", e.getMessage());
			return null;
		} finally {
			image.delete();
		}

		return tmpImagePath;
	}

	public Integer getResPicDelIndex() {
		return resPicDelIndex;
	}

	public void setResPicDelIndex(Integer resPicDelIndex) {
		this.resPicDelIndex = resPicDelIndex;
	}

	public Integer getAttPicDelIndex() {
		return attPicDelIndex;
	}

	public void setAttPicDelIndex(Integer attPicDelIndex) {
		this.attPicDelIndex = attPicDelIndex;
	}

	public String getShowPreviewFlg() {
		return showPreviewFlg;
	}

	public void setShowPreviewFlg(String showPreviewFlg) {
		this.showPreviewFlg = showPreviewFlg;
	}

	public String getParentid() {
		return parentid;
	}

	public void setParentid(String parentid) {
		this.parentid = parentid;
	}

	public AreaInfoDto getAreaDto() {
		return areaDto;
	}

	public void setAreaDto(AreaInfoDto areaDto) {
		this.areaDto = areaDto;
	}

	public String getShowMapFlg() {
		return showMapFlg;
	}

	public void setShowMapFlg(String showMapFlg) {
		this.showMapFlg = showMapFlg;
	}

	public List<Map<String, String>> getTypeList() {
		return typeList;
	}

	public void setTypeList(List<Map<String, String>> typeList) {
		this.typeList = typeList;
	}

	public String getGoodsClass() {
		return goodsClass;
	}

	public void setGoodsClass(String goodsClass) {
		this.goodsClass = goodsClass;
	}

	public String getDelIds() {
		return delIds;
	}

	public void setDelIds(String delIds) {
		this.delIds = delIds;
	}

	public String getClassification() {
		return classification;
	}

	public void setClassification(String classification) {
		this.classification = classification;
	}
}
